
package ogame.utilities;

import java.util.ArrayList;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

/**
 *
 * @author scchang
 */
public class OgameNumericField extends JTextField{

    public OgameNumericField(int cols){
        super(cols);
    }
    
    @Override
    protected Document createDefaultModel(){
        return new NumericDocument();
    }
    
    static class NumericDocument extends PlainDocument {
        
        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException{
            if (str == null){
                return;
            }
            ArrayList<Character> results = new ArrayList<>(str.length());
            for(int i = 0; i < str.length(); ++i){
                try{
                    // This is the shittest way in the world to do it
                    int integer = Integer.parseInt(""+str.charAt(i));
                    results.add((""+integer).charAt(0));
                }catch(NumberFormatException e){
                    continue;
                }
            }
            if(results.isEmpty()){
                return;
            }
            
            Character[] character_array = results.toArray(new Character[1]);
            char[] char_array = new char[character_array.length];
            for(int i = 0; i < char_array.length; ++i){
                char_array[i] = character_array[i];
            }
            super.insertString(offs, new String(char_array), a);
        }
    }

}
